package com.laoxu.java.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**向服务器发送需要进行倒序排序的字符串
 * @author laoxu
 * @create 2017-12-23
 **/
public class Reverse {
    public static void main(String[] args) throws Exception{
        String[] arr = {"http://localhost:8080/helloweb/ReverseServlet","eM esreverR"};

        if(arr.length !=2){
            System.err.println("Usage:  java Reverse "
                    + "http://<location of your servlet/script>"
                    + " string_to_reverse");
            System.exit(1);
        }

        String stringToReverse = URLEncoder.encode(arr[1],"UTF-8");
        URL url = new URL(arr[0]);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);

        //拿到输出流，向服务器发送信息
        PrintWriter out = new PrintWriter(connection.getOutputStream());
        out.write("string=" + stringToReverse);
        out.flush();
        out.close();

        //拿到输入流，读取服务端发回信息
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String decodeString;
        while ((decodeString=in.readLine())!=null){
            System.out.println(decodeString);
        }

        in.close();

    }
}
